import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'dart:async';
import 'dart:io';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';
import './person.dart';

class DetailsInfoProvide with ChangeNotifier{
  
   var goodsInfo = null;
   List comment = null;
   String test = 'aaa';
   String ID = '';
   bool isLeft = true;
   bool isRight = false;
   String LOCALURL = 'http://dianshan.free.idcfengye.com'; // 基础网址

  //从后台获取商品信息
  getGoodsInfo(String id)async{
    ID = id;
    var formData = { 'goodsId':id };
    Dio dio = new Dio();
    dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
    Response response = await dio.post(LOCALURL + "/goods/getDetailGoodsInfo",data: formData);
    var data = json.decode(response.toString());
    print(response);
    goodsInfo = data['message'];
    // 获取评论
    response = await dio.post(LOCALURL + "/goods/getComment",data: formData);
    data = json.decode(response.toString());
    print(data);
    comment = data['comment'];
    print('护手霜护手霜上海市');
    print(response);
    notifyListeners();
  }
  //改变tabBar的状态
  changeLeftAndRight(String changeState){
    if(changeState=='left'){
      print('跑到左边了');
      isLeft=true;
      isRight=false;
    }else{
      isLeft=false;
      isRight=true;
    }
     notifyListeners();
  }

  // 发送评论
  void postComment(i,token,context) async {
    if(token==''){
      Fluttertoast.showToast(
        msg: '请先登录再评论！！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      return;
    }
    var formData = {
      'comment':i,
      'goodsId':ID,
      'goodsName': goodsInfo['NAME']
    };
    Dio dio = new Dio();
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        // 在请求被发送之前做一些事情
        print('被发送之前');
        return options; //continue
        // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
        // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
        //
        // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
        // 这样请求将被中止并触发异常，上层catchError会被调用。
        },
        onResponse:(Response response) {
        // 在返回响应数据之前做一些预处理
        print("响应之前");
        // print(response.headers);
        return response; // continue
        },
        onError: (DioError e) {
          // 当请求失败时做一些预处理
          print('请求失败了');
          // print(e.response.data);
          if(e.response.statusCode==401){
            Fluttertoast.showToast(
              msg: '登录过期，请重新登录',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIos: 1,
              backgroundColor: Theme.of(context).primaryColor,
              textColor: Colors.white,
              fontSize: 16.0
            );
            Provide.value<PersonnalProvider>(context).out();
          }
          print(e.response.statusCode);
          // print(e.response.headers);
          // print(e.response.request);
        return e;//continue
        }
    ));
    // dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
    Response response = await dio.post(LOCALURL + "/goods/comment",data: formData,options: options);
    
    var data = json.decode(response.toString());
    if(data['code']==200){
      Fluttertoast.showToast(
        msg: data['message'],
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      // 发送评论后要刷新评论
      getComment();
    }else {
      Fluttertoast.showToast(
        msg: "评论提交出错",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
    }
    notifyListeners();
  }

  // 获取评论
  void getComment()async{
    var formData = { 'goodsId': ID };
    Dio dio = new Dio();
    dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
    Response response = await dio.post(LOCALURL + "/goods/getComment",data: formData);
    var data = json.decode(response.toString());
    print(data);
    comment = data['comment'];
    notifyListeners();
  }

  // 马上购买
  void buy(goodsId,goodsName,count,price,images,context,token,username)async{
    Map<String, dynamic> newGoods={
      'goodsId':goodsId,
      'goodsName':goodsName,
      'count':count,
      'price':price,
      'images':images,
      'isCheck':true
    };
    List postList = [];// 临时存储要提交的商品
    postList.add(newGoods);
    Dio dio = new Dio();
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        // 在请求被发送之前做一些事情
        print('被发送之前');
        return options; //continue
        },
        onResponse:(Response response) {
        // 在返回响应数据之前做一些预处理
        print("响应之前");
        // print(response.headers);
        return response; // continue
        },
        onError: (DioError e) {
          // 当请求失败时做一些预处理
          print('请求失败了');
          // print(e.response.data);
          if(e.response.statusCode==401){
            Fluttertoast.showToast(
              msg: '登录过期，请重新登录',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIos: 1,
              backgroundColor: Theme.of(context).primaryColor,
              textColor: Colors.white,
              fontSize: 16.0
            );
            Provide.value<PersonnalProvider>(context).out();
          }
          print(e.response.statusCode);
        return e;//continue
        }
    ));
    var formData = {
      'userName': username,
      'cart': postList
    };
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/postCart',options: options,data: formData);
    var data = json.decode(response.toString());
    Fluttertoast.showToast(
      msg: data['message'],
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
    Navigator.pop(context);
  }
}